// Navigation Helper - Shared logic for bottom navigation
// This script should be included in all pages that need dynamic navigation

function getMerchantStatus() {
    // First priority: Check stored merchant data (set by login or demo)
    const merchantData = localStorage.getItem('merchantData');
    if (merchantData) {
        try {
            const data = JSON.parse(merchantData);
            return {
                loggedIn: true,
                approved: data.approved || false,
                merchantId: data.merchantId,
                companyName: data.companyName,
                status: data.status || (data.approved ? '已通过' : '审核中')
            };
        } catch (e) {
            // Invalid JSON, clear and fallback
            localStorage.removeItem('merchantData');
        }
    }
    
    // Second priority: Check URL parameters (for demo)
    const urlParams = new URLSearchParams(window.location.search);
    const statusParam = urlParams.get('status');
    
    if (statusParam === 'approved') {
        return { loggedIn: true, approved: true, status: '已通过' };
    } else if (statusParam === 'pending') {
        return { loggedIn: true, approved: false, status: '审核中' };
    } else {
        // Default: not logged in
        return { loggedIn: false, approved: false, status: '未登录' };
    }
}

function updateBottomNavigation() {
    // Check if this is a B2B page (merchant already logged in and approved)
    const currentPage = getCurrentPageType();
    if (currentPage === 'b2b') {
        // For B2B pages, navigation is static: 首页, 数据, 我的
        return; // No dynamic updates needed for B2B pages
    }

    // For C2C pages, maintain original dynamic center button logic
    const centerNav = document.getElementById('center-nav');
    if (!centerNav) return; // Skip if no center nav element

    const merchantStatus = getMerchantStatus();

    if (merchantStatus.loggedIn) {
        if (merchantStatus.approved) {
            // Logged in and approved - show management center
            centerNav.href = 'merchant-center.html';
            centerNav.innerHTML = `
                <div class="w-12 h-12 mx-auto -mt-2 bg-gradient-to-r from-indigo-600 to-purple-600 rounded-full flex items-center justify-center shadow-lg">
                    <i class="fas fa-store text-white text-lg"></i>
                </div>
                <p class="text-xs text-indigo-600 mt-1">管理</p>
            `;
        } else {
            // Logged in but not approved - show status query
            centerNav.href = 'application-status.html';
            centerNav.innerHTML = `
                <div class="w-12 h-12 mx-auto -mt-2 bg-gradient-to-r from-orange-500 to-orange-600 rounded-full flex items-center justify-center shadow-lg">
                    <i class="fas fa-hourglass-half text-white text-lg"></i>
                </div>
                <p class="text-xs text-orange-600 mt-1">审核中</p>
            `;
        }
    } else {
        // Not logged in - show entry/register
        centerNav.href = 'merchant-entry.html';
        centerNav.innerHTML = `
            <div class="w-12 h-12 mx-auto -mt-2 bg-gradient-to-r from-indigo-600 to-purple-600 rounded-full flex items-center justify-center shadow-lg">
                <i class="fas fa-plus text-white text-lg"></i>
            </div>
            <p class="text-xs text-gray-600 mt-1">入驻</p>
        `;
    }
}

// Determine current page type
function getCurrentPageType() {
    const path = window.location.pathname;
    const filename = path.split('/').pop();

    if (filename.startsWith('b2b-') || filename === 'merchant-center.html') {
        return 'b2b';
    } else {
        return 'c2c';
    }
}

// Standard bottom navigation HTML template
function getBottomNavigationHTML(currentPage = '') {
    const pages = {
        'home': { href: 'home-b2c.html', icon: 'fa-home', text: '首页' },
        'dashboard': { href: 'b2b-dashboard.html', icon: 'fa-chart-bar', text: '数据' },
        'logistics': { href: 'logistics-hub.html', icon: 'fa-truck', text: '物流' },
        'merchant': { href: 'merchant-center.html', icon: 'fa-store', text: '管理' }
    };
    
    let html = '<div class="absolute bottom-0 left-0 right-0 bg-white border-t border-gray-200"><div class="flex justify-around py-2" id="bottom-nav">';
    
    // Home
    const homeClass = currentPage === 'home' ? 'text-indigo-600' : 'text-gray-400';
    html += `<a href="${pages.home.href}" class="flex-1 text-center py-2">
                <i class="fas ${pages.home.icon} text-xl ${homeClass} mb-1"></i>
                <p class="text-xs ${homeClass}">${pages.home.text}</p>
             </a>`;
    
    // Dashboard
    const dashboardClass = currentPage === 'dashboard' ? 'text-indigo-600' : 'text-gray-400';
    html += `<a href="${pages.dashboard.href}" class="flex-1 text-center py-2">
                <i class="fas ${pages.dashboard.icon} text-xl ${dashboardClass} mb-1"></i>
                <p class="text-xs ${dashboardClass}">${pages.dashboard.text}</p>
             </a>`;
    
    // Dynamic Center Button
    html += `<a href="merchant-entry.html" class="flex-1 text-center py-2 relative" id="center-nav">
                <div class="w-12 h-12 mx-auto -mt-2 bg-gradient-to-r from-indigo-600 to-purple-600 rounded-full flex items-center justify-center shadow-lg">
                    <i class="fas fa-plus text-white text-lg"></i>
                </div>
                <p class="text-xs text-gray-600 mt-1">入驻</p>
             </a>`;
    
    // Logistics
    const logisticsClass = currentPage === 'logistics' ? 'text-indigo-600' : 'text-gray-400';
    html += `<a href="${pages.logistics.href}" class="flex-1 text-center py-2">
                <i class="fas ${pages.logistics.icon} text-xl ${logisticsClass} mb-1"></i>
                <p class="text-xs ${logisticsClass}">${pages.logistics.text}</p>
             </a>`;
    
    // Profile/My
    const profileClass = currentPage === 'profile' ? 'text-indigo-600' : 'text-gray-400';
    html += `<a href="b2b-profile.html" class="flex-1 text-center py-2">
                <i class="fas fa-user text-xl ${profileClass} mb-1"></i>
                <p class="text-xs ${profileClass}">我的</p>
             </a>`;
    
    html += '</div></div>';
    return html;
}

// Initialize navigation when DOM is loaded
function initializeNavigation(currentPage = '') {
    document.addEventListener('DOMContentLoaded', function() {
        updateBottomNavigation();
        
        // Listen for localStorage changes from other tabs/windows
        window.addEventListener('storage', function(e) {
            if (e.key === 'merchantData') {
                // Merchant status changed in another tab
                updateBottomNavigation();
                
                // Trigger custom event for pages that need to update other elements
                const event = new CustomEvent('merchantStatusChanged', {
                    detail: getMerchantStatus()
                });
                document.dispatchEvent(event);
            }
        });
        
        // Also listen for custom events within the same page
        document.addEventListener('merchantStatusChanged', function(e) {
            updateBottomNavigation();
        });
    });
}

// Trigger navigation update across all frames
function triggerNavigationSync() {
    // Update current page
    updateBottomNavigation();
    
    // Dispatch event for same-page listeners
    const event = new CustomEvent('merchantStatusChanged', {
        detail: getMerchantStatus()
    });
    document.dispatchEvent(event);
    
    // For iframe communication, we'll use postMessage
    if (window.parent !== window) {
        window.parent.postMessage({
            type: 'merchantStatusChanged',
            status: getMerchantStatus()
        }, '*');
    }
    
    // Send message to all child frames
    const frames = document.querySelectorAll('iframe');
    frames.forEach(frame => {
        try {
            frame.contentWindow.postMessage({
                type: 'merchantStatusChanged',  
                status: getMerchantStatus()
            }, '*');
        } catch (e) {
            // Cross-origin iframe, ignore
        }
    });
}

// Listen for iframe messages
function setupIframeMessaging() {
    window.addEventListener('message', function(e) {
        if (e.data && e.data.type === 'merchantStatusChanged') {
            updateBottomNavigation();
        }
    });
}

// Logout function
function merchantLogout() {
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('merchantData');
        window.location.href = 'merchant-entry.html';
    }
}